package com.tth.learn.addproperties.java;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;

/**
 * DateTimeFormatter：日期格式化
 * @Author tth
 * @Date 2022/12/7 15:58
 */
public class Java8DateTimeFormatterTest {
    public static void main(String[] args) {
        // 实例化1：通过预定义的标准格式，如ISO_LOCAL_TIME、ISO_LOCAL_DATE、ISO_LOCAL_DATE_TIME
        DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        // 格式化：日期 --> 字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String s = dtf.format(localDateTime);
        System.out.println(localDateTime + " --> " +s);
        // 解析： 字符串 --> 日期
        TemporalAccessor parse = dtf.parse("2022-12-07T16:04:03.594");
        System.out.println(parse); // {},ISO resolved to 2022-12-07T16:04:03.594

        // 实例化2：通过本地化相关的格式，如DateTimeFormatter.ofLocalizedDateTime()(适用的参数为FormatStyle.SHORT、FormatStyle.MEDIUM、FormatStyle.LONG)、
        // DateTimeFormatter.ofLocalizedDate()(适用的参数为FormatStyle.SHORT、FormatStyle.MEDIUM、FormatStyle.LONG、FormatStyle.FULL)
        DateTimeFormatter dtf1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
        String s1 = dtf1.format(localDateTime);
        System.out.println(localDateTime + " --> " +s1); // 2022-12-07T16:09:18.095 --> 22-12-7 下午4:09
        DateTimeFormatter dtf2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
        String s2 = dtf2.format(localDateTime);
        System.out.println(localDateTime + " --> " +s2); // 2022-12-07T16:09:18.095 --> 2022-12-7 16:09:18
        DateTimeFormatter dtf3 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        String s3 = dtf3.format(localDateTime);
        System.out.println(localDateTime + " --> " +s3); // 2022-12-07T16:09:18.095 --> 2022年12月7日 下午04时09分18秒
        DateTimeFormatter dtf4 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        LocalDate localDate = LocalDate.now();
        String s4 = dtf4.format(localDate);
        System.out.println(localDate + " --> " +s4); // 2022-12-07 --> 2022年12月7日 星期三

        // 实例化3：通过自定义的格式，如DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        DateTimeFormatter dtf5 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化
        String s5 = dtf5.format(localDateTime);
        System.out.println(localDateTime + " --> " +s5); // 2022-12-07T16:19:37.665 --> 2022-12-07 16:19:37
        // 解析
        TemporalAccessor parse1 = dtf5.parse("2022-11-11 08:08:08");
        System.out.println(parse1); // {},ISO resolved to 2022-12-07T16:04:03.594

    }
}
